package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.addAddressBook(addressBook);
    }
    /**
     * 根据用户ID查询所有地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBooks = addressBookMapper.listByUserId(userId);
        return addressBooks;
    }
    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddressBook() {
        Long userId = BaseContext.getCurrentId();
        return addressBookMapper.getDefaultAddressBook(userId);
    }
    /**
     * 根据ID修改地址
     * @param addressBook
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBookMapper.updata(addressBook);
    }
    /**
     * 根据ID删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.deleteById(id,userId);
    }
    /**
     * 根据ID查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getADDressBookById(Long id) {
        Long userId = BaseContext.getCurrentId();
        AddressBook result=addressBookMapper.getADDressBookById(id,userId);
        return result;
    }
    /**
     * 设置默认地址
     * @param defaultAddressBookId
     */
    @Override
    @Transactional
    public void updateDefaultAddressBook(AddressBook defaultAddressBookId) {
        Long userId = BaseContext.getCurrentId();
        //查询原有的默认地址
        AddressBook addressBook = addressBookMapper.getDefaultAddressBook(userId);
        //如果存在，将原有的默认地址取消
        if (addressBook != null) {
            addressBook.setIsDefault(0);
            addressBookMapper.updata(addressBook);
        }
        addressBook=new AddressBook();
        addressBook.setId(defaultAddressBookId.getId());
        addressBook.setIsDefault(1);
        addressBookMapper.updata(addressBook);
    }
}
